﻿using System.Diagnostics.CodeAnalysis;

namespace BindTryParseMVC.Models
{
    public class DateRange : IParsable<DateRange>
    {
        public DateOnly? From { get; init; }
        public DateOnly? To { get; init; }

        public static DateRange Parse(string s, IFormatProvider? provider)
        {
            if(!TryParse(s, provider, out var result))
            {
                throw new ArgumentException($"Cannot parse '{s}' to DateRange.");
            }
            return result;
        }

        public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out DateRange result)
        {
            var segments = s?.Split(",", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
            if(segments?.Length==2
                && DateOnly.TryParse(segments[0],provider,out var fromDate)
                && DateOnly.TryParse(segments[1], provider, out var toDate))
            {
                result = new DateRange
                {
                    From = fromDate,
                    To = toDate
                };
                return true;
            }
            result = new DateRange { From=default, To = default };
            return false;
        }
    }
}
